﻿@using JsViewEngine
@model JsViewEngine.Demo.Models.MoviesViewModel

@{
    ViewBag.Title = "Compiling named templates from strings";
}

<h3>Compiling named templates from strings</h3>

<form method="GET">
    <input type="hidden" name="details" class="removeOnEnhance" value="@((this.Model.ShowDetails != true).ToString())"/>
    <button type="submit" id="switchBtn">
        @(this.Model.ShowDetails == true ? "Show titles only" : "Show full details")
    </button><br/>
</form>
<br />
<table>
    <tbody id="movieList">
        @if (Model.ShowDetails.HasValue) {
            @Html.Partial(Model.ShowDetails == true ? "detailTemplate" : "titleTemplate", Model.Movies)
        }
    </tbody>
</table>


@section scripts
{
    @Scripts.Render("~/bundles/jsrender")

    <script type="text/javascript">
        var movies = @JsTemplates.ObjectToJson(Model.Movies);

        /* Compile markup as named templates */
        $.templates({
            titleTemplate: "@JsTemplates.RenderTemplateString("titleTemplate")",
            detailTemplate: "@JsTemplates.RenderTemplateString("detailTemplate")"
        });
        
        var details = @((Model.ShowDetails ?? false).ToString().ToLower());
        
        function switchTemplates() {
            var html;

            details = !details;

            /* Render using the other named template */
            if (details) {
                $(this).text("Show titles only");
                html = $.render.detailTemplate(movies);
            } else {
                $(this).text("Show full details");
                html = $.render.titleTemplate(movies);
            }
            
            $( "#movieList" ).html( html );
            
            // Fix up the URL query string if possible
            // TODO: doesn't work with the Back button.
            history && history.pushState({ }, document.title, "?details=" + details);
        }

        $(".removeOnEnhance").remove();
        $("#switchBtn").unwrap();
        $("#switchBtn").click(function(event) {
            // can't change the type of the button, so stop the submission of the form
            event.preventDefault();
            
            switchTemplates();
        });

        /* Not needed with pre-rendered template
            * switchTemplates();
            */
    </script>
}